package com.tao.springai.controller;

import com.tao.springai.service.ChatHistoryService;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/api/chat")
@CrossOrigin(origins = "*")
public class ChatHistoryController {

    private final ChatHistoryService chatHistoryService;

    public ChatHistoryController(ChatHistoryService chatHistoryService) {
        this.chatHistoryService = chatHistoryService;
    }

    /**
     * 创建新的聊天会话
     */
    @PostMapping("/sessions")
    public ResponseEntity<?> createSession(@RequestBody Map<String, String> request) {
        String title = request.getOrDefault("title", "新对话");
        String sessionId = chatHistoryService.createSession(title);
        
        Map<String, String> response = new HashMap<>();
        response.put("sessionId", sessionId);
        return ResponseEntity.ok(response);
    }

    /**
     * 更新会话标题
     */
    @PutMapping("/sessions/{sessionId}/title")
    public ResponseEntity<?> updateSessionTitle(
            @PathVariable String sessionId,
            @RequestBody Map<String, String> request) {
        
        String title = request.get("title");
        if (title == null || title.isEmpty()) {
            return ResponseEntity.badRequest().body("Title is required");
        }
        
        boolean updated = chatHistoryService.updateSessionTitle(sessionId, title);
        if (updated) {
            return ResponseEntity.ok().build();
        } else {
            return ResponseEntity.notFound().build();
        }
    }

    /**
     * 获取会话历史消息
     */
    @GetMapping("/sessions/{sessionId}/messages")
    public ResponseEntity<?> getSessionMessages(@PathVariable String sessionId) {
        return ResponseEntity.ok(chatHistoryService.getMessages(sessionId));
    }

    /**
     * 获取最近的会话列表（本周）
     */
    @GetMapping("/sessions/recent")
    public ResponseEntity<?> getRecentSessions() {
        return ResponseEntity.ok(chatHistoryService.getRecentSessions());
    }

    /**
     * 获取较早的会话列表（本周之前）
     */
    @GetMapping("/sessions/older")
    public ResponseEntity<?> getOlderSessions() {
        return ResponseEntity.ok(chatHistoryService.getOlderSessions());
    }

    /**
     * 添加消息到会话
     */
    @PostMapping("/sessions/{sessionId}/messages")
    public ResponseEntity<?> addMessage(
            @PathVariable String sessionId,
            @RequestBody Map<String, Object> request) {
        
        String content = (String) request.get("content");
        boolean isUser = (boolean) request.getOrDefault("isUser", true);
        
        chatHistoryService.addMessage(sessionId, content, isUser);
        return ResponseEntity.ok().build();
    }
} 